package cn.com.sina.finance.todolist.adapter;

import android.content.Context;
import android.view.View;

import androidx.annotation.NonNull;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import cn.com.sina.finance.todolist.R;
import cn.com.sina.finance.todolist.base.BaseRecyclerAdapter;
import cn.com.sina.finance.todolist.base.ViewHolder;
import cn.com.sina.finance.todolist.bean.ApiResponse;
import cn.com.sina.finance.todolist.bean.TodoBean;
import cn.com.sina.finance.todolist.event.DeleteTodoEvent;
import cn.com.sina.finance.todolist.net.HttpCallback;
import cn.com.sina.finance.todolist.net.HttpUtil;
import cn.com.sina.finance.todolist.util.ToastUtil;

/**
 * @author yuebo
 * @date 2024/9/30
 */
public class TodoListAdapter extends BaseRecyclerAdapter<TodoBean> {

    public TodoListAdapter(Context context) {
        super(context);
    }

    @Override
    public int getItemLayoutId() {
        return R.layout.item_todo;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position, TodoBean data) {
        holder.setText(R.id.tvTodoId, data.todoId + "");
        holder.setText(R.id.tvTodoContent, data.todo);
        holder.setOnClickListener(R.id.btnItemDelete, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delete(data);
            }
        });
    }

    private void delete(TodoBean todoBean) {
        String url = "http://chenyuebo.cn/deleteTodo?todoId=" + todoBean.todoId;
        HttpUtil.get(url, new HttpCallback() {
            @Override
            public void onSuccess(String data) {
                ApiResponse response = new Gson().fromJson(data, ApiResponse.class);
                if (response != null && response.code == 0) {
                    ToastUtil.showLongToast(context, "删除成功");
                    EventBus.getDefault().post(new DeleteTodoEvent());
                }
            }

            @Override
            public void onFail(int code, String msg, Throwable e) {
                ToastUtil.showLongToast(context, msg);
            }
        });
    }
}
